import { login, logout, getInfo, register, forgetPassword } from '@/api/user';
import { getToken, setToken, removeToken } from '@/utils/auth';
import { resetRouter } from '@/router';

import tim from '@/tim';
const user = {
  state: {
    token: getToken(),
    shopInfo: {
      name: '',
      avatar: '',
      logo: '',
      roles: [],
      membersType: 0 // 1: 诚信商家 2: 品牌商家 0: 免费商家
    },
    // 会员充值跟续费条件
    renewMembersCondition: [{
      type: 1,
      deposit: 1000, // 保证金
      price: 3988 // 会员费
    }, {
      type: 2,
      deposit: 30000,
      price: 6988
    }],
    // 头部任务列表
    taskList: [{
      id: 1,
      title: '恭喜您成功入驻佰材网，请先完善您的店铺信息（完成可获得1信用分）',
      path: 'Information',
      linkName: '去完善',
      isCompleted: false
    },
    {
      id: 2,
      title: '为获得更多权益，请您先进行诚信认证（完成可获得1信用分）',
      path: 'ShopAuthCredit',
      linkName: '去认证',
      isCompleted: false
    },
    {
      id: 3,
      title: '为享受全部权益，请您先进行品牌认证（完成可获得1信用分）',
      path: 'ShopAuthBrand',
      linkName: '去认证',
      isCompleted: false
    },
    {
      id: 4,
      title: '您尚未上架过商品，请先上传商品（完成可获得1信用分）',
      path: 'GoodsAdd',
      linkName: '去上传',
      isCompleted: false
    },
    {
      id: 5,
      title: '您尚未创建过商家活动，请先创建活动（完成可获得1信用分）',
      path: 'AdAdd',
      linkName: '去创建',
      isCompleted: false
    },
    {
      id: 6,
      title: '您尚未创建过商家优惠券，请先创建优惠券（完成可获得1信用分）',
      path: 'CouponList',
      linkName: '去创建',
      isCompleted: false
    }],
    test: 1,
    members: {
      type: 0, // 1: 诚信商家 2: 品牌商家 0: 免费商家
      start: 0,
      end: 0,
      deposit: '',
      price: ''

      // type: 1,
      // start: 1583120149369,
      // end: 1583120149369,
      // deposit: 1000, // 保证金
      // price: 1000 // 会员费

      // type: 2,
      // start: 1583120149369,
      // end: 1583120149369,
      // deposit: 1000,
      // price: 3988

    },
    // 消息message // zancun
    message: {
      // type: 0, // 0 交易消息 1 退款消息 2警告与处罚 3其他消息
      // title: '新订单',
      // content: '用户“张三” 已下单商品“桥梁伸缩缝 d80型 160型桥梁伸缩装置 定制 国标”',
      // orderId: '123456',
      // date: '2019-12-11  11:20:15'
      type: 1, // 0 交易消息 1 退款消息 2警告与处罚 3其他消息
      title: '新订单',
      content: '用户“张三” 已下单商品“桥梁伸缩缝 d80型 160型桥梁伸缩装置 定制 国标”',
      orderId: '123456',
      date: '2019-12-11  11:20:15'
    },
    // TIM
    currentUserProfile: {},
    isLogin: false,
    isSDKReady: false, // TIM SDK 是否 ready
    userID: '',
    userSig: '',
    sdkAppID: 0
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token;
    },
    SET_INFO: (state, info) => {
      state.shopInfo = info;
    },
    // 修改任务是否完成的状态
    modifyTask: (state, payload) => {
      state.taskList.forEach(task => {
        if (task.id === payload.id) task.isCompleted = payload.isCompleted;
      });
    },
    // TIM
    updateCurrentUserProfile(state, userProfile) {
      state.currentUserProfile = userProfile;
    },
    toggleIsLogin(state, isLogin) {
      state.isLogin = typeof isLogin === 'undefined' ? !state.isLogin : isLogin;
    },
    toggleIsSDKReady(state, isSDKReady) {
      state.isSDKReady = typeof isSDKReady === 'undefined' ? !state.isSDKReady : isSDKReady;
    },
    reset(state) {
      Object.assign(state, {
        currentUserProfile: {},
        isLogin: false,
        isSDKReady: false // TIM SDK 是否 ready
      });
    },
    GET_USER_INFO(state, payload) {
      state.userID = payload.userID;
      state.userSig = payload.userSig;
      state.sdkAppID = payload.sdkAppID;
    },
    SET_USERID(state, id) {
      state.userID = id;
    }
  },

  actions: {
    // user login
    login({ commit }, userInfo) {
      const { phone, password } = userInfo;
      return new Promise((resolve, reject) => {
        login({ phone: phone.trim(), password: password }).then(({ data }) => {
          commit('SET_TOKEN', data);
          setToken(data);
          resolve();
        }).catch(error => {
          reject(error);
        });
      });
    },

    // get user info
    getInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo(state.token).then(({ data }) => {
          if (!data) {
            reject('登录失败，请重新登录');
          }
          const { roles, avatar, name, summary, logo, mainimage, introduce, phone, taskState } = data;

          // roles must be a non-empty array
          if (!roles || roles.length <= 0) {
            reject('getInfo: roles must be a non-null array!');
          }
          commit('SET_USERID', phone);
          commit('SET_INFO', data);
          const TASKSTATE = Number(taskState);
          for (let i = 1; i <= TASKSTATE; i++) {
            commit('modifyTask', { id: i, isCompleted: true });
          }
          // 修改是否完善了店铺信息
          if (avatar !== 'web/public/avatar.png' && logo !== 'web/public/init-logo.png' && name.indexOf('`') === -1 && summary && mainimage && introduce) {
            commit('modifyTask', { id: 1, isCompleted: true });
          } else {
            commit('modifyTask', { id: 1, isCompleted: false });
          }
          resolve(data);
        }).catch(error => {
          reject(error);
        });
      });
    },
    // user register
    register({ commit }, data) {
      const { phone, password, code, avatar, logo, mainimage } = data;
      return new Promise((resolve, reject) => {
        register({ phone, password, code, avatar, logo, mainimage }).then(response => {
          resolve(data);
        }).catch(error => {
          reject(error);
        });
      });
    },
    // user forgetPassword
    forgetPassword({ commit }, data) {
      const { phone, password, code } = data;
      return new Promise((resolve, reject) => {
        forgetPassword({ phone, password, code }).then(response => {
          resolve(data);
        }).catch(error => {
          reject(error);
        });
      });
    },
    // user logout
    sysLogout({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '');
          // commit('SET_ROLES', []);
          removeToken();
          resetRouter();
          resolve();
        }).catch(error => {
          reject(error);
        });
      });
    },

    // remove token
    resetToken({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '');
        // commit('SET_ROLES', []);
        removeToken();
        resolve();
      });
    },

    // TIM
    logout(context) {
      // 若有当前会话，在退出登录时已读上报
      if (context.rootState.conversation.currentConversation.conversationID) {
        tim.setMessageRead({
          conversationID: context.rootState.conversation.currentConversation.conversationID
        });
      }
      tim.logout().then(() => {
        context.commit('toggleIsLogin');
        context.commit('stopComputeCurrent');
        context.commit('reset');
      });
    }
  }
};
export default user;

